package com.printhelper.controller;

import com.printhelper.dto.ApiResponse;
import com.printhelper.model.Conversion;
import com.printhelper.service.PdfToPptService;
import com.printhelper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/convert")
@CrossOrigin(origins = "*")
public class ConvertController {
    
    @Autowired
    private PdfToPptService pdfToPptService;
    
    @Autowired
    private UserService userService;
    
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<Conversion>> uploadPdf(@RequestParam("file") MultipartFile file) {
        try {
            // Get current user
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            String userId = userService.findByUsername(username).get().getId();
            
            // Validate file
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Please select a file to upload"));
            }
            
            if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Only PDF files are allowed"));
            }
            
            // Convert PDF to PPT
            Conversion conversion = pdfToPptService.convertPdfToPpt(file, userId);
            
            return ResponseEntity.ok(ApiResponse.success("File uploaded and conversion started", conversion));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("Error processing file: " + e.getMessage()));
        }
    }
    
    @GetMapping("/download/{conversionId}")
    public ResponseEntity<Resource> downloadPpt(@PathVariable String conversionId) {
        try {
            // Get current user
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            String userId = userService.findByUsername(username).get().getId();
            
            // Get conversion
            Conversion conversion = pdfToPptService.getConversion(conversionId);
            
            if (conversion == null) {
                return ResponseEntity.notFound().build();
            }
            
            // Check if user owns this conversion
            if (!conversion.getUserId().equals(userId)) {
                return ResponseEntity.status(403).build();
            }
            
            // Check if conversion is completed
            if (!"COMPLETED".equals(conversion.getStatus())) {
                return ResponseEntity.badRequest().build();
            }
            
            // Get PPT file
            Path pptPath = Paths.get(conversion.getPptFilePath());
            if (!Files.exists(pptPath)) {
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new FileSystemResource(pptPath.toFile());
            
            return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, 
                    "attachment; filename=\"" + conversion.getOriginalFileName().replace(".pdf", ".pptx") + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
                
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/history")
    public ResponseEntity<ApiResponse<List<Conversion>>> getHistory() {
        try {
            // Get current user
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            String userId = userService.findByUsername(username).get().getId();
            
            List<Conversion> conversions = pdfToPptService.getUserConversions(userId);
            
            return ResponseEntity.ok(ApiResponse.success("Conversion history retrieved", conversions));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("Error retrieving history: " + e.getMessage()));
        }
    }
    
    @GetMapping("/status/{conversionId}")
    public ResponseEntity<ApiResponse<Conversion>> getStatus(@PathVariable String conversionId) {
        try {
            // Get current user
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            String userId = userService.findByUsername(username).get().getId();
            
            Conversion conversion = pdfToPptService.getConversion(conversionId);
            
            if (conversion == null) {
                return ResponseEntity.notFound().build();
            }
            
            // Check if user owns this conversion
            if (!conversion.getUserId().equals(userId)) {
                return ResponseEntity.status(403).build();
            }
            
            return ResponseEntity.ok(ApiResponse.success("Conversion status retrieved", conversion));
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("Error retrieving status: " + e.getMessage()));
        }
    }
} 